from config_env import BASE_URL, USERNAME, PASSWORD
from utils.http_client import http_request, Method

GET_TOKEN_URL = BASE_URL + '/tokens'

_current_token = None

def get_token(account, password):
    data = {'account': account, 'password': password}
    result = http_request(Method.POST, GET_TOKEN_URL, json=data)
    if isinstance(result, dict) and 'token' in result:
        return result['token']
    raise Exception(f"Token获取失败: {result.get('error', '未知错误')}")

def get_current_token():
    global _current_token
    if _current_token is None:
        refresh_token()
    return _current_token['token']

def refresh_token():
    global _current_token
    _current_token = get_token(USERNAME, PASSWORD)
